package com.vcredit.bird.service.creditTips;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.vcredit.creditcat.redis.RedisServiceExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.bird.service.base.BirdResponse;
import com.vcredit.bird.service.base.BirdService;
import com.vcredit.bird.util.BirdConstants;
import com.vcredit.bird.vo.creditEntiy.CreditEntityResponse;
import com.vcredit.bird.vo.creditEntiy.CreditTipsVo;
import com.vcredit.creditcat.exception.BirdRequestException;
import com.vcredit.creditcat.util.ConcurrentDateUtil;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.JacksonUtil;

/**
 * 信用帖查询服务接口
 *
 * @author zhangboshi
 *
 */
@Service
public class CreditTipsService extends BirdService {

	@Autowired
	private RedisServiceExt redisService;
	// 信用帖查询url
	@Value("${creditTips.credit51}")
	private String credit51Url;
	@Value("${creditTips.creditChina}")
	private String creditChinaUrl;
	@Value("${creditTips.creditLearning}")
	private String creditLearningUrl;
	@Value("${creditTips.kashen8}")
	private String kashen8Url;
	@Value("${creditTips.tjjr}")
	private String tjjrUrl;
	@Value("${creditTips.u51}")
	private String u51Url;

	/**
	 * 访问蜂鸟数据
	 *
	 */
	private List<CreditEntityResponse> creditTipsQuery(String requestUrl) {
		CreditTipsVo response = null;
		try {
			BirdResponse birdResponse = super.getBirdData(requestUrl);
			response = JacksonUtil.Json2Obj(birdResponse.getResult(), new TypeReference<CreditTipsVo>() {
			});
		} catch (Exception e) {
			new BirdRequestException("我爱卡json解析失败");
		}
		return response == null ? null : response.getCreditTips();
	}

	/**
	 * 数据保存redis方法
	 *
	 * @param response
	 */
	private void saveDataToRedis(Map<Integer, List<CreditEntityResponse>> response) {
		if (null != response) {
			if (null == redisService.get(BirdConstants.CREDIT_ENTITY_KEY)) {
				redisService.put(BirdConstants.CREDIT_ENTITY_KEY, response, BirdConstants.REDIS_CREDIT_ENTITY_EXPIRED);
			} else {
				redisService.del(BirdConstants.CREDIT_ENTITY_KEY);
				redisService.put(BirdConstants.CREDIT_ENTITY_KEY, response, BirdConstants.REDIS_CREDIT_ENTITY_EXPIRED);
			}
		}
	}

	/**
	 * 按照序号从新排序
	 *
	 * @param resultList
	 */
	private void collectionsSort(List<CreditEntityResponse> resultList) {
		Collections.sort(resultList, new Comparator<CreditEntityResponse>() {
			@Override
			public int compare(CreditEntityResponse item1, CreditEntityResponse item2) {
				try {
					Date d1 = ConcurrentDateUtil.getDate(item1.getTime());
					Date d2 = ConcurrentDateUtil.getDate(item2.getTime());
					if(d1.equals(d2))
						return 0;
					return d1.before(d2) ? 1 : -1;
				}catch (Exception e){
					return -1;
				}
			}
		});
	}

	/**
	 * 信用贴士查询
	 *
	 * @return
	 * @throws BirdRequestException
	 */
	@Log
	public List<CreditEntityResponse> creditEntityQuery() throws BirdRequestException {
		LinkedList<CreditEntityResponse> resultList = new LinkedList<CreditEntityResponse>();
		// 访问蜂鸟数据
		List<CreditEntityResponse> credit51 = creditTipsQuery(credit51Url);
		List<CreditEntityResponse> creditChina = creditTipsQuery(creditChinaUrl);
		List<CreditEntityResponse> creditLearning = creditTipsQuery(creditLearningUrl);
		List<CreditEntityResponse> kashen8 = creditTipsQuery(kashen8Url);
		List<CreditEntityResponse> tjjr = creditTipsQuery(tjjrUrl);
		List<CreditEntityResponse> u51 = creditTipsQuery(u51Url);
		if (!Utility.isNullOrEmpty(credit51)) {
			resultList.addAll(credit51);
		}
		if (!Utility.isNullOrEmpty(creditChina)) {
			resultList.addAll(creditChina);
		}
		if (!Utility.isNullOrEmpty(creditLearning)) {
			resultList.addAll(creditLearning);
		}
		if (!Utility.isNullOrEmpty(kashen8)) {
			resultList.addAll(kashen8);
		}
		if (!Utility.isNullOrEmpty(tjjr)) {
			resultList.addAll(tjjr);
		}
		if (!Utility.isNullOrEmpty(u51)) {
			resultList.addAll(u51);
		}
		// 按照序号从新排序
		this.collectionsSort(resultList);
		// List数据分段存储Map集合方法
		Map<Integer, List<CreditEntityResponse>> creditEntityMap = this.listSaveToMap(resultList);
		// 数据保存redis
		this.saveDataToRedis(creditEntityMap);
		return resultList;
	}

	/**
	 * List数据分段存储Map集合方法
	 *
	 * @param source
	 * @return
	 */
	private Map<Integer, List<CreditEntityResponse>> listSaveToMap(List<CreditEntityResponse> source) {
		Map<Integer, List<CreditEntityResponse>> map = new HashMap<Integer, List<CreditEntityResponse>>();
		// 用map存起来新的分组后数据,每20条数据一组
		int k = 0;
		List<CreditEntityResponse> savelist = null;
		List<CreditEntityResponse> newlist = null;
		for (int i = 0; i < source.size(); i += BirdConstants.PAGESIZE) {
			savelist = source.subList(i, Math.min(source.size(), (i + BirdConstants.PAGESIZE)));
			newlist = new ArrayList<CreditEntityResponse>(savelist);
			map.put(k, newlist);
			k++;
		}
		return map;
	}
}
